package com.example.rabbitdemo.services;

import com.example.rabbitdemo.config.RabbitmqConfig;
import com.example.rabbitdemo.entity.Test;
import com.example.rabbitdemo.mapper.TestMapper;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RabbitMqReceiver {

    @Autowired
    private TestMapper testMapper;

    /**
     * 消息接收者
     *
     * @param msg 消息体
     * @return
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                    exchange = @Exchange(value = RabbitmqConfig.DIRECT_EXCHANGE,type = ExchangeTypes.DIRECT),
                    value = @Queue(value = RabbitmqConfig.DIRECT_QUEUE1),
                    key = "demo"
            )
    })
    public void receiver1(String msg) {
        System.out.println("Direct模式--Queue1接收到的消息:" + msg);
    }


    @RabbitListener(bindings = {
            @QueueBinding(
                    exchange = @Exchange(value = RabbitmqConfig.DIRECT_EXCHANGE,type = ExchangeTypes.DIRECT),
                    value = @Queue(value = RabbitmqConfig.DIRECT_QUEUE2),
                    key = "demo2"
            )
    })
    public void receiver2(String msg) {
        Test queue = Test.builder().topic("")
                .context(msg)
                .queue(RabbitmqConfig.DIRECT_QUEUE2).build();
        testMapper.addOne(queue);

        System.out.println("Direct模式--Queue2接收到的消息:" + msg);
    }


    @RabbitListener(bindings = {
            @QueueBinding(
                    exchange = @Exchange(value = RabbitmqConfig.TOPIC_EXCHANGE,type = ExchangeTypes.TOPIC),
                    value = @Queue(value = RabbitmqConfig.TOPIC_QUEUE1),
                    key = "topic.one"
            )
    })
    public void listenTopicOne(String msg){
        System.out.println("Topic模式--Queue1接收到的消息:" + msg);
    }


    @RabbitListener(bindings = {
            @QueueBinding(
                    exchange = @Exchange(value = RabbitmqConfig.TOPIC_EXCHANGE,type = ExchangeTypes.TOPIC),
                    value = @Queue(value = RabbitmqConfig.TOPIC_QUEUE2),
                    key = "topic.#"
            )
    })
    public void listenTopic(String msg){
        System.out.println("Topic模式--Queue2接收到的消息:" + msg);
    }


    @RabbitListener(queues = RabbitmqConfig.FANOUT_QUEUE1)
    public void listenFanoutOne(String msg){
        System.out.println("Fanout模式--Queue1接收到的消息:" + msg);
    }

    @RabbitListener(queues = RabbitmqConfig.FANOUT_QUEUE2)
    public void listenFanout(String msg){
        System.out.println("Fanout模式--Queue2接收到的消息:" + msg);
    }

}
